import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import { Header } from '../common/header';
import { AtInput } from 'taro-ui'
import '../common/header.scss'
import './search.scss';
import QQMapWX from '../../utils/qqmap-wx-jssdk.min'
import { connect } from '@tarojs/redux'
import { State, Props } from './index.interface'

@connect(({ address }) => ({
    ...address,
}))

export class AddressSearch extends Component<State, Props> {
    state = {
        qqmapsdk: new QQMapWX({
            key: 'UI2BZ-ACGWD-5B244-HYLE4-MKLE5-2RBJY'
        }),
        sug: []
    }
    constructor(props: Props) {
        super(props);
    }

    componentDidMount() {
        Taro.getLocation({
            type: 'wgs84',
            success(res) {
                console.log(res);
            }
        })
    }

    async handleSelect(item) {
        const { dispatch } = this.props;
        await dispatch({
            type: 'addressSearch/setSug',
            payload: { sug: item }
        })
    }

    handleChange(value) {
        let __this = this;
        this.state.qqmapsdk.getSuggestion({
            //获取输入框值并设置keyword参数
            keyword: value, //用户输入的关键词，可设置固定值,如keyword:'KFC'
            region: '长沙', //设置城市名，限制关键词所示的地域范围，非必填参数
            success: async function (res) {//搜索成功后的回调
                var sug = [];
                for (var i = 0; i < res.data.length; i++) {
                    sug.push({
                        title: res.data[i].title,
                        id: res.data[i].id,
                        addr: res.data[i].address,
                        city: res.data[i].city,
                        district: res.data[i].district,
                        latitude: res.data[i].location.lat,
                        longitude: res.data[i].location.lng
                    });
                }
                __this.setState({
                    sug
                });
            },
            fail: function (error) {
                console.error(error);
            },
            complete: function (res) {
                console.log(res);
            }
        });
    }

    onClickLeftIcon(){
        Taro.navigateBack();
    }
    render() {
        return (<View>
            <Header leftIconType='chevron-left'
                onClickLeftIcon={this.onClickLeftIcon}
                title='选择地址'></Header>
            <View style={{ 'backgroundColor': '#fff' }}>
                <AtInput name='address' type='text' placeholder='输入地址' onChange={this.handleChange.bind(this)} />
                <View className="search-address">
                    {
                        this.state.sug.map(function (item) {
                            return <View onClick={this.handleSelect.bind(this, item)}>{item.title}</View>
                        })
                    }
                </View>
            </View>
        </View>)
    }
}